package csu.web.mypetstore.controller;

import csu.web.mypetstore.pojo.Category;
import csu.web.mypetstore.service.CategoryService;
import csu.web.mypetstore.service.ImageService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ImageService imageService;



    @GetMapping("deleteCategory")
    @Transactional
    public String updateCategory(@RequestParam String categoryId) {
        categoryService.deleteCategory(categoryId);
        return "redirect:cmsMainForm";
    }
    @GetMapping("updateCategory")
    @Transactional
    public String updateCategory(HttpSession session, @RequestParam("categoryid") String categoryId, @RequestParam("name") String categoryName, @RequestParam("description") String description, @RequestParam("image") MultipartFile image) {

        // Category category = categoryService.getCategory(oldCategoryId);
         Category category = categoryService.getCategory(categoryId);
         category.setCatid(categoryId);
         category.setName(categoryName);
         if(image!=null)
         {
             category.setDescn(imageService.saveImage(image, categoryName)+description);

         }
         else
         {
             category.setDescn(category.getImage()+ description);
         }

        categoryService.updateCategory(category);
        return "redirect:cmsMainForm";
    }
    @PostMapping("addCategory")
    @Transactional
    public String addCategory(@RequestParam("categoryid") String categoryId, @RequestParam("name") String categoryName, @RequestParam("description") String description, @RequestParam("image") MultipartFile image) {
        Category category = new Category();
        category.setCatid(categoryId);
        category.setName(categoryName);
        category.setDescn(imageService.saveImage(image, categoryName) + description);
        categoryService.insertCategory(category);
        return "redirect:cmsMainForm";
    }


}
